package radar

import (
	"context"
	"git.mycaigou.com/gfyx/common/tenant_db"
	"git.mycaigou.com/gfyx/micro-gfyx-oppty-service/infrastructure/common/constants"
	"gorm.io/gorm"
	"time"
)

type GfyxRadarSubscriptionConfigRepos struct {
	tenant_db.TenantDB
}

func NewRadarSubscriptionConfigRepos() GfyxRadarSubscriptionConfigReposIface {
	return &GfyxRadarSubscriptionConfigRepos{}
}

func (g *GfyxRadarSubscriptionConfigRepos) AddRadarSubscriptionConfig(ctx context.Context, data *GfyxRadarSubscriptionConfig) error {
	data.CreatedOn = time.Now()
	data.ModifiedOn = time.Now()
	err := g.GetTenantDB(ctx).Create(data).Error
	if err != nil {
		return err
	}
	return nil
}

func (g *GfyxRadarSubscriptionConfigRepos) SaveRadarSubscriptionConfig(ctx context.Context, data *GfyxRadarSubscriptionConfig) error {
	data.CreatedOn = time.Now()
	data.ModifiedOn = time.Now()
	err := g.GetTenantDB(ctx).Save(data).Error
	if err != nil {
		return err
	}
	return nil
}

func (g *GfyxRadarSubscriptionConfigRepos) GetRadarSubscriptionConfigByUser(ctx context.Context, userGUID string) (*GfyxRadarSubscriptionConfig, error) {
	radarSubscriptionConfig := &GfyxRadarSubscriptionConfig{}
	err := g.GetTenantDB(ctx).
		Where("user_guid = ?", userGUID).
		Order("created_on desc").First(radarSubscriptionConfig).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return radarSubscriptionConfig, err
	}
	return radarSubscriptionConfig, nil
}

func (g *GfyxRadarSubscriptionConfigRepos) GetAllRadarSubscriptionConfig(ctx context.Context) ([]*GfyxRadarSubscriptionConfig, error) {
	var list []*GfyxRadarSubscriptionConfig
	err := g.GetTenantDB(ctx).Where("is_deleted = ?", constants.IsDeletedFalse).Find(&list).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}
	return list, nil
}
